//
//  TravelNotesViewController.m
//  ITrip
//
//  Created by dlios on 15-5-21.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TravelNotesViewController.h"
#import "TravelNotesParser.h"
#import "TravelNotesTableViewCell.h"
#import "TravelNotesModel.h"
#import "TravelNotesSecondViewController.h"
#import "URLPath.h"
#import "SetViewController.h"

#import <MJRefresh.h>
#import <SDImageCache.h>
#import <AFNetworking.h>

@interface TravelNotesViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

@property(nonatomic, retain) UITableView *tView;
@property(nonatomic, retain) NSMutableArray *arrayData;
@property(nonatomic, assign) NSInteger number;
@property(nonatomic, assign) NSInteger numberStr;


@end

@implementation TravelNotesViewController

- (void)dealloc
{
    [_tView release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    NSString *path = [NSString string];
    // 下载
    // 创建一个AFN管理对象
    if (self.numberStrategy == 0) {
         path = [URLPath travelNotesURL];
        // 装饰导航栏
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
        title.text = @"  爱     旅";
        title.font = [UIFont systemFontOfSize:20];
        title.font = [UIFont boldSystemFontOfSize:25];
        title.textColor = [UIColor whiteColor];
        self.navigationItem.titleView = title;
        
        self.arrayData = [NSMutableArray array];
//        UIImage *set = [UIImage imageNamed:@"iconfont-shezhi"];
//        set = [set imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:set style:UIBarButtonItemStyleDone target:self action:@selector(setSystem)];
        
        
    } else {
        UIImage *icon = [UIImage imageNamed:@"iconfont_return"];
        icon = [icon imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
         self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStyleDone target:self action:@selector(getBack)];
        path = [NSString stringWithFormat:@"http://chanyouji.com/api/destinations/trips/%ld.json?month=0&", self.numberStrategy];
        NSLog(@"%ld", self.numberStrategy);
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 告诉AFN不要解析
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    NSString *params = @"page=1";
    [manager GET:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.arrayData = [TravelNotesParser getParser:operation.responseData];
        [self initTableView];
        [activityIndicator stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        [activityIndicator stopAnimating];
        alert.delegate = self;
        [alert show];
    }];
 
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
        NSString *path = [NSString string];
        self.arrayData = [NSMutableArray array];
        // 下载
        if (self.numberStrategy == 0) {
            path = [URLPath travelNotesURL];
        } else {
            path = [NSString stringWithFormat:@"http://chanyouji.com/api/destinations/trips/%ld.json?month=0&", self.numberStrategy];
        }
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *params = @"?page=1";
        [manager GET:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            self.arrayData = [TravelNotesParser getParser:operation.responseData];
            [self.tView reloadData];
            [self initTableView];
            [activityIndicator stopAnimating];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
            [activityIndicator stopAnimating];
        }];
    

}

// 返回按钮
- (void)getBack
{
    [self.navigationController popViewControllerAnimated:YES];
}


// 初始化tableview
- (void)initTableView
{
    self.tView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.tView];
    [self.tView release];
    self.tView.delegate = self;
    self.tView.dataSource = self;
    self.tView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(reFresh)];
    self.tView.showsVerticalScrollIndicator = NO;
    self.number = 1;
    self.numberStr = 1;
    // 下拉
    [self.tView addLegendHeaderWithRefreshingBlock:^{
        self.numberStr = 1;
        self.number = 1;
        NSString *path = [NSString string];
        self.arrayData = [NSMutableArray array];
        // 下载
        if (self.numberStrategy == 0) {
             path = [URLPath travelNotesURL];
        } else {
//            NSLog(@"1");
            path = [NSString stringWithFormat:@"http://chanyouji.com/api/destinations/trips/%ld.json?month=0&", self.numberStrategy];
        }
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *params = @"?page=1";
        [manager GET:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            self.arrayData = [TravelNotesParser getParser:operation.responseData];
            [self.tView.header endRefreshing];
            [self.tView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }];
    }];
}

- (void)reFresh
{
    [self.tView.legendFooter beginRefreshing];
    NSString *path = [NSString string];
    
    if (self.numberStrategy == 0) {
        self.numberStr++;
        NSString *num = [NSString stringWithFormat:@"%ld", self.numberStr];
        path = [URLPath travelNotesURL];
        path = [path stringByAppendingFormat:@"?page=%@", num];
//        NSLog(@"%@", path);
    } else {
        self.number++;
        NSString *num = [NSString stringWithFormat:@"%ld", self.number];
        path = [NSString stringWithFormat:@"http://chanyouji.com/api/destinations/trips/%ld.json?month=0&", self.numberStrategy];
        path = [path stringByAppendingFormat:@"page=%@",num];
//        NSLog(@"1");
    }
    
    // 下载
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
        [self.arrayData addObjectsFromArray:[TravelNotesParser getParser:operation.responseData]];
        [self.tView reloadData];
        [self.tView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.tView.footer endRefreshing];
        [self.tView reloadData];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
    }];
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelNotesSecondViewController *travelNotesSecond = [[TravelNotesSecondViewController alloc] init];
    if (self.numberStrategy != 0) {
        travelNotesSecond.isJourney = 1;
    }
    
    [self.navigationController pushViewController:travelNotesSecond animated:YES];
    TravelNotesModel *model = [TravelNotesModel getModel];
    if (self.arrayData.count > indexPath.row && indexPath.row >= 0) {
        model = [self.arrayData objectAtIndex:indexPath.row];
    }
    travelNotesSecond.number = model.id;
//    NSLog(@"%ld", model.id);
    travelNotesSecond.days = model.days;
//    [travelNotesSecond release];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    TravelNotesTableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[TravelNotesTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    TravelNotesModel *model = [TravelNotesModel getModel];
    if (self.arrayData.count > indexPath.row && indexPath.row >= 0) {
        model = [self.arrayData objectAtIndex:indexPath.row];
    }
    [cell setTravelNotesModel:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240;
}

// 设置按钮方法
- (void)setSystem
{
    SetViewController *setView = [[SetViewController alloc] init];
    [self.navigationController pushViewController:setView animated:YES];
    [setView release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
